<?php
    class Admincp_FashionController extends Main_Controller_Action
    {
        private $_arrParam;
        private $_model;
        private $_validate;
        
        public function init()
        {
            $this->loadTemplates('admin');
            $this->_arrParam = $this->_request->getParams();
            $this->_model = new Admincp_Model_Fashion();
            $this->_validate = new Admincp_Form_ValidateFashion();
            $this->view->headTitle('Quản lý đồ thời trang');
        }
        
        public function preDispatch()
        {
            $auth = Zend_Auth::getInstance();
            if(!$auth->hasIdentity()) {
                if($this->_request->getActionName() != 'login')
                    $this->_redirect('admincp/index/login');
            }
        }
        
        public function indexAction()
        {
            if($_POST['add']) {
                $this->_redirect('admincp/fashion/create');
            }
            if($_POST['delete']) {
                $listId = $this->_arrParam['check'];
			    $this->_model->deleteMultiItem($listId);
			    $this->_redirect($_SERVER['HTTP_REFERER']);
            }
            $category = new Admincp_Model_Fashioncategory();
            $this->view->category = $category->listItemForProduct();
            
            $adapter = new Zend_Paginator_Adapter_DbSelect($this->_model->listItem());
			$paginator = new Zend_Paginator($adapter);
			$paginator->setItemCountPerPage(40);
			$paginator->setPageRange(5);
			$currentPage = $this->_request->getParam('page', 1);
			$paginator->setCurrentPageNumber($currentPage);
			$this->view->data = $paginator;
			$this->view->total = $paginator->getTotalItemCount();
        }
        
        public function createAction()
        {
            $category = new Admincp_Model_Fashioncategory();
            $this->view->category = $category->listItemForProduct();
            
            if($this->_request->isPost()) {
                $name           = trim(strip_tags($this->_arrParam['name']));
                $category_id    = (int) $this->_arrParam['category'];
                $price          = trim(strip_tags($this->_arrParam['price']));
                $sale_price     = trim(strip_tags($this->_arrParam['sale_price']));
                $color          = trim(strip_tags($this->_arrParam['color']));
                $size           = trim(strip_tags($this->_arrParam['size']));
                $description    = stripslashes($this->_arrParam['description']);
                $upload         = new Zend_File_Transfer_Adapter_Http();
                $info           = $upload->getFileInfo();
                $image          = $upload->getFileName('image', false);
                $flag           = true;
                
                $this->view->descriptionValue = $description;
                if($this->_validate->validName($name)) {
                    $this->view->nameValue = $name;
                }
                else {
                    $this->view->errorName = 'Tên sản phẩm từ 1-100 kí tự';
                    $flag = false;
                }
                if($this->_validate->validPrice($price)) {
                    $this->view->priceValue = $price;
                }
                else {
                    $this->view->errorPrice = 'Giá tiền từ 1-10 kí tự số';
                    $flag = false;
                }
                if($sale_price !== '') {
                    if($this->_validate->validPrice($sale_price)) {
                        $this->view->salePriceValue = $sale_price;
                    }
                    else {
                        $this->view->errorSalePrice = 'Giá tiền từ 1-10 kí tự số';
                        $flag = false;
                    }
                }
                if($color !== '') {
                    if($this->_validate->validName($color)) {
                        $this->view->colorValue = $color;
                    }
                    else {
                        $this->view->errorColor = 'Màu sắc không quá 100 kí tự';
                        $flag = false;
                    }
                }
                if($size !== '') {
                    if($this->_validate->validName($size)) {
                        $this->view->sizeValue = $size;
                    }
                    else {
                        $this->view->errorSize = 'Kích thước không quá 100 kí tự';
                        $flag = false;
                    }
                }
                $upload->addValidator('Size', false, 4800000)
                       ->addValidator('Extension', false, 'jpg,jpeg,png,gif');
                if(!$upload->isValid()) {
                    $this->view->errorImage = 'Ảnh phải đúng định dạng (jpeg, jpg, png, gif) và dung lượng tối đa 4 MB';
                    $flag = false;
                }
                if(!$this->_validate->validImage($image)) {
                    $this->view->errorImage = 'Ảnh phải đúng định dạng (jpeg, jpg, png, gif) và dung lượng tối đa 4 MB';
                    $flag = false;
                }
                
                if($flag == true) {
					$image = strtolower($image);
                    $resize = new Image_Resize();
                    preg_match('#\.([^\.]+)$#', $image, $matches);
                    $fileExtension  = $matches[1];
                    $fileName = 'pic_' . time() . mt_rand(5, 99999999);
                    $newFileName = $fileName . '.' . $fileExtension;
                    $image_info = getimagesize($info['image']['tmp_name']);
                    $resize->load($info['image']['tmp_name']);
                    if($image_info[0] > 400) {
                        $resize->resizeToWidth(400);
                        $resize->save(BASE_PATH.'/public/files/fashion/'.$newFileName);
                    }
                    else {
                        $resize->save(BASE_PATH.'/public/files/fashion/'.$newFileName);
                    }
                    if($image_info[0] > 270) {
                        $resize->resizeToWidth(270);
                        $resize->save(BASE_PATH.'/public/files/fashion/thumbnail/'.$newFileName);
                    }
                    else {
                        $resize->save(BASE_PATH.'/public/files/fashion/thumbnail/'.$newFileName);
                    }

                    $strFlex = new Zendvn_Filter_RemoveCircumflex();
                    $data = array(
                        'name' => $name,
                        'image' => $newFileName,
                        'thumbnail' => $newFileName,
                        'price' => $price,
                        'sale_price' => $sale_price,
                        'size' => $size,
                        'color' => $color,
                        'description' => $description,
                        'create_date' => date('Y-m-d'),
                        'url' => strtolower($strFlex->filter2($name)),
                        'status' => 1,
                        'category_id' => $category_id,
                        'type' => 1,
                    );
                    $this->_model->saveItem($data, 'create');
                    $this->_redirect('admincp/fashion');
                }
            }
        }
        
        public function editAction()
        {
            $id = (int) $this->_arrParam['id'];
            $this->view->data = $this->_model->getItem($id);
            $category = new Admincp_Model_Fashioncategory();
            $this->view->category = $category->listItemForProduct();
            
            if($this->_request->isPost()) {
                $name           = trim(strip_tags($this->_arrParam['name']));
                $category_id    = (int) $this->_arrParam['category'];
                $price          = trim(strip_tags($this->_arrParam['price']));
                $sale_price     = trim(strip_tags($this->_arrParam['sale_price']));
                $color          = trim(strip_tags($this->_arrParam['color']));
                $size           = trim(strip_tags($this->_arrParam['size']));
                $description    = stripslashes($this->_arrParam['description']);
                $upload         = new Zend_File_Transfer_Adapter_Http();
                $info           = $upload->getFileInfo();
                $image          = $upload->getFileName('image', false);
                $flag           = true;
                
                if(!$this->_validate->validName($name)) {
                    $this->view->errorName = 'Tên sản phẩm từ 1-100 kí tự';
                    $flag = false;
                }
                if(!$this->_validate->validPrice($price)) {
                    $this->view->errorPrice = 'Giá tiền từ 1-10 kí tự số';
                    $flag = false;
                }
                if($sale_price !== '') {
                    if(!$this->_validate->validPrice($sale_price)) {
                        $this->view->errorSalePrice = 'Giá tiền từ 1-10 kí tự số';
                        $flag = false;
                    }
                }
                if($color !== '') {
                    if(!$this->_validate->validName($color)) {
                        $this->view->errorColor = 'Màu sắc không quá 100 kí tự';
                        $flag = false;
                    }
                }
                if($size !== '') {
                    if(!$this->_validate->validName($size)) {
                        $this->view->errorSize = 'Kích thước không quá 100 kí tự';
                        $flag = false;
                    }
                }
                
                if($flag == true) {
                    $strFlex = new Zendvn_Filter_RemoveCircumflex();
                    $data = array(
                        'id' => $id,
                        'name' => $name,
                        'price' => $price,
                        'sale_price' => $sale_price,
                        'size' => $size,
                        'color' => $color,
                        'description' => $description,
                        'url' => strtolower($strFlex->filter2($name)),
                        'category_id' => $category_id,
                    );
                    
                    if($this->_validate->validImage($image)) {
                        $upload->addValidator('Size', false, 4800000)
                               ->addValidator('Extension', false, 'jpg,jpeg,png,gif');
                        if(!$upload->isValid()) {
                            $this->view->errorImage = 'Ảnh phải đúng định dạng (jpeg, jpg, png, gif) và dung lượng tối đa 4 MB';
                        }
                        else {
        					$image = strtolower($image);
                            preg_match('#\.([^\.]+)$#', $image, $matches);
                            $fileExtension  = $matches[1];
                            $fileName = 'pic_' . time() . mt_rand(5, 99999999);
                            $newFileName = $fileName . '.' . $fileExtension;
                            $image_info = getimagesize($info['image']['tmp_name']);
                            
                            $resize = new Image_Resize();
                            $resize->load($info['image']['tmp_name']);
                            if($image_info[0] > 400) {
                                $resize->resizeToWidth(400);
                                $resize->save(BASE_PATH.'/public/files/fashion/'.$newFileName);
                            }
                            else {
                                $resize->save(BASE_PATH.'/public/files/fashion/'.$newFileName);
                            }
                            if($image_info[0] > 270) {
                                $resize->resizeToWidth(270);
                                $resize->save(BASE_PATH.'/public/files/fashion/thumbnail/'.$newFileName);
                            }
                            else {
                                $resize->save(BASE_PATH.'/public/files/fashion/thumbnail/'.$newFileName);
                            }
                            $data['image'] = $newFileName;
                            $data['thumbnail'] = $newFileName;
                            $this->_model->saveItem($data, 'update');
                            if(is_file(PUBLIC_PATH . '/files/fashion/' . $this->view->data['image'])) {
    							@unlink(PUBLIC_PATH . '/files/fashion/' . $this->view->data['image']);
    						}
                            if(is_file(PUBLIC_PATH . '/files/fashion/thumbnail/' . $this->view->data['thumbnail'])) {
    							@unlink(PUBLIC_PATH . '/files/fashion/thumbnail/' . $this->view->data['thumbnail']);
    						}
                            $this->_redirect('admincp/fashion');
                        }
                    }
                    else {
                        $this->_model->saveItem($data, 'update');
                        $this->_redirect('admincp/fashion');
                    }
                }
            }
        }
        
        public function deleteAction()
        {
            $id = (int) $this->_arrParam['id'];
		    $this->_model->deleteItem($id);
		    $this->_redirect($_SERVER['HTTP_REFERER']);
        }
        
        public function publishAction()
		{
		    $id = (int) $this->_arrParam['id'];
		    $status = (int) $this->_arrParam['status'];
		    $status = ($status == 1) ? 2 : 1;
		    $data = array(
                'id' => $id,
		        'status' => $status,
		    );
		    $this->_model->saveItem($data, 'update');
		    $this->_redirect($_SERVER['HTTP_REFERER']);
		}
        
        public function searchAction()
		{
            $category = new Admincp_Model_Fashioncategory();
            $this->view->category = $category->listItemForProduct();

		    $strFlex = new Zendvn_Filter_RemoveCircumflex();
		    $name = strtolower(trim($strFlex->filter(strip_tags($this->_arrParam['name']))));
		    $status = (int) $this->_arrParam['status'];
            $category_id = (int) $this->_arrParam['category_id'];
            $start_price = trim(strip_tags($this->_arrParam['start_price']));
            $end_price = trim(strip_tags($this->_arrParam['end_price']));
		    $this->view->keyword = array(
	            'name' => $this->_arrParam['name'],
	            'status' => $this->_arrParam['status'],
                'category_id' => $this->_arrParam['category_id'],
                'start_price' => $this->_arrParam['start_price'],
                'end_price' => $this->_arrParam['end_price'],
		    );
		    $data = array(
	            'name' => (string) '%'.str_replace(' ','%',$name).'%',
	            'status' => $status,
                'category_id' => $category_id,
                'start_price' => $start_price,
                'end_price' => $end_price,
		    );
		    $adapter = new Zend_Paginator_Adapter_DbSelect($this->_model->searchItem($data));
		    $paginator = new Zend_Paginator($adapter);
		    $paginator->setItemCountPerPage(40);
		    $paginator->setPageRange(5);
		    $currentPage = $this->_request->getParam('page', 1);
		    $paginator->setCurrentPageNumber($currentPage);
		    $this->view->data = $paginator;
		    $this->view->total = $paginator->getTotalItemCount();
		}
    }
